package com.cdn.allmobilestore.activity;

import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Menu;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.cdn.allmobilestore.R;
import com.cdn.allmobilestore.adapter.FragmentPagerAdapter;
import com.cdn.allmobilestore.model.Campaign;
import com.cdn.allmobilestore.service.AllMobileStoreWebService;
import com.cdn.allmobilestore.ui.BaseFragment;
import com.cdn.allmobilestore.ui.CategoryFragment;
import com.cdn.allmobilestore.ui.HomeFragment;
import com.cdn.allmobilestore.ui.ListAppFragment;
import com.cdn.allmobilestore.ui.MoreFragment;
import com.cdn.allmobilestore.ulti.AllMobileReference;
import com.cdn.allmobilestore.ulti.Constant;
import com.cdn.allmobilestore.ulti.GlobalApplication;
import com.cdn.allmobilestore.ulti.Log;
import com.cdn.allmobilestore.widget.TabIndicator;

public class MainTabActivity extends BaseActivity implements FragmentPagerAdapter.TabChangedListener, View.OnClickListener,OnPageChangeListener  {
	private String MAINTAB_CATEGORY_ID ="0";
	private ViewPager mPager;
	private String mCurrentTag = Constant.FRAGMENT_TAG_HOME;
	private View mTabContainerBg;
	private TabIndicator tab_home,tab_topapp,tab_category,tab_more;
	BaseFragment homeFragment,topappFragment,accountFragment,menuFragment;
	BaseFragment categoryFragment;
	
    private FragmentPagerAdapter mPagerAdapter;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		 registerGCM();
		setCustomContentView(R.layout.activity_main);
		//setContentView(R.layout.activity_main);		
		mTabContainerBg = findViewById(R.id.tab_container_bg);
		this.tab_home = ((TabIndicator)findViewById(R.id.tab_indicator_home));
	    this.tab_topapp = ((TabIndicator)findViewById(R.id.tab_indicator_topapp));
	    this.tab_category = ((TabIndicator)findViewById(R.id.tab_indicator_category));
	    this.tab_more = ((TabIndicator)findViewById(R.id.tab_indicator_account));
		mPager = (ViewPager) findViewById(R.id.tab_pager);
		
		Log.v(Environment.DIRECTORY_DOWNLOADS);
		
		FragmentManager localFragmentManager = getSupportFragmentManager();
	    FragmentTransaction localFragmentTransaction = localFragmentManager.beginTransaction();
	    
	    homeFragment = (BaseFragment)localFragmentManager.findFragmentByTag(Constant.FRAGMENT_TAG_HOME);
	    if(homeFragment == null)
	    {
	    	homeFragment = new HomeFragment();
	    	localFragmentTransaction.add(R.id.tab_pager,homeFragment,Constant.FRAGMENT_TAG_HOME);
	    }
	    	
	    topappFragment = (BaseFragment)localFragmentManager.findFragmentByTag(Constant.FRAGMENT_TAG_DOWNLOAD);
	    if(topappFragment == null)
	    {
	    	topappFragment = new ListAppFragment();
	    	((ListAppFragment) topappFragment).setCategory(MAINTAB_CATEGORY_ID);
	    	 localFragmentTransaction.add(R.id.tab_pager,topappFragment,Constant.FRAGMENT_TAG_DOWNLOAD);
	    }
	    
	    categoryFragment = (BaseFragment)localFragmentManager.findFragmentByTag(Constant.FRAGMENT_TAG_CATEGORY);
	    if(categoryFragment == null)
	    {
	    	categoryFragment = new CategoryFragment();
	    	((CategoryFragment) categoryFragment).setCategory(MAINTAB_CATEGORY_ID);
	    	localFragmentTransaction.add(R.id.tab_pager,categoryFragment,Constant.FRAGMENT_TAG_CATEGORY);
	    }
	    
	    accountFragment = (BaseFragment)localFragmentManager.findFragmentByTag(Constant.FRAGMENT_TAG_MORE);
	    if(accountFragment == null)
	    {
	    	accountFragment = new MoreFragment();
	    	localFragmentTransaction.add(R.id.tab_pager,accountFragment,Constant.FRAGMENT_TAG_MORE);
	    }
	    
	    mPager.setOnPageChangeListener(this);
	    mPagerAdapter = new FragmentPagerAdapter(getSupportFragmentManager());
	    mPagerAdapter.setTabChangedListener(this);
		mPagerAdapter.addFragment(tab_home, homeFragment);		
		mPagerAdapter.addFragment(tab_topapp,topappFragment);
		mPagerAdapter.addFragment(tab_category, categoryFragment);
		mPagerAdapter.addFragment(tab_more, accountFragment);
		mPagerAdapter.setContext(this);
		
		if (!localFragmentTransaction.isEmpty())
	     {
	        localFragmentTransaction.commitAllowingStateLoss();
	        getSupportFragmentManager().executePendingTransactions();
	     }
		int currentTab = mPagerAdapter.getPositionByTag(this.mCurrentTag);
		
	    this.mPagerAdapter.selectTab(currentTab);
	   // 	   
	    mPager.setAdapter(mPagerAdapter);
	    mPager.setCurrentItem(currentTab);

	    setHomeButtonEnable(false);
	    setSearchButtonEnable(true);
	    
	    
	   
	}
	
	
	
	
	/* (non-Javadoc)
	 * @see android.support.v4.app.FragmentActivity#onResume()
	 */
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		//check for advertising
	    super.setDisplayPopUp(false);
	    if(GlobalApplication._().getmCampaign().hasCampaign() && !GlobalApplication._().getmCampaign().isShow()){
	    	Campaign mCampaign = GlobalApplication._().getmCampaign();
	    	mCampaign.setShow(true);
	    	super.getAdvFragment().loadUrl(mCampaign.getmCampaignPromoUrl());
	    	super.setDisplayPopUp(true);
	    }
	}




	@Override
	 public void onWindowFocusChanged(boolean hasFocus) {
	    super.onWindowFocusChanged(hasFocus);
	   /* if(GlobalApplication._().isFirstTime(true))
	    {
	    	int moreTab = mPagerAdapter.getPositionByTag(Constant.FRAGMENT_TAG_MORE);
		    this.mPagerAdapter.selectTab(moreTab);
		    this.mPager.setCurrentItem(moreTab);
		    scrollTab(moreTab, 0);
	    }
	    */ 	    
	 }
	
	private void registerGCM() {
		Boolean isRegisterGCM = AllMobileReference
				.getRegisterGCMState(this);
		
		Log.v("registerGCM:" + isRegisterGCM);
		
		if (!isRegisterGCM) {
			AllMobileStoreWebService.registerDevice(this);
		}
	}
	

	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		//getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	public static void setCurrentTag(MainTabActivity activity, String tag)
	{
		activity.mCurrentTag = tag;
	}
	
	
	

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		
	}


	
	@Override
	public void onBackPressed() {
		if(mNumBack < 1 )
		{
			Toast.makeText(this, getString(R.string.press_back_exist), Toast.LENGTH_SHORT).show();
			mNumBack ++;
		}			
		else
		{			
			super.onBackPressed();
		}
					
	}
	
	@Override
	public void onConfigurationChanged(Configuration newConfig) {

		setRequestedOrientation(Configuration.ORIENTATION_PORTRAIT); // otherwise lock in portrait
		
		super.onConfigurationChanged(newConfig);
	}
	

	@Override
	public void onTabChanged(int position) {
		// TODO Auto-generated method stub
		this.mPager.setCurrentItem(position);
		//((TabIndicator) this.mPager.getChildAt(position)).setTextAppearance(this, R.style.TextAppearance_Button_Action);
	
		
	}
	@Override
	 protected void onRestoreInstanceState(Bundle paramBundle)
	  {
	    super.onRestoreInstanceState(paramBundle);
	    RelativeLayout.LayoutParams localLayoutParams = (RelativeLayout.LayoutParams)this.mTabContainerBg.getLayoutParams();
	    localLayoutParams.leftMargin = paramBundle.getInt("tabLeftMargin");
	    localLayoutParams.rightMargin = paramBundle.getInt("tabRightMargin");
	    
	    this.mTabContainerBg.setLayoutParams(localLayoutParams);
	  }
    
	@Override
	  protected void onSaveInstanceState(Bundle paramBundle)
	  {
	    RelativeLayout.LayoutParams localLayoutParams = (RelativeLayout.LayoutParams)this.mTabContainerBg.getLayoutParams();
	    paramBundle.putInt("tabLeftMargin", localLayoutParams.leftMargin);
	    paramBundle.putInt("tabRightMargin", localLayoutParams.rightMargin);
	    super.onSaveInstanceState(paramBundle);
	  }

		public void scrollTab(int position,float positionOffset)
		{	
			 
			 RelativeLayout.LayoutParams localLayoutParams = (RelativeLayout.LayoutParams)MainTabActivity.this.mTabContainerBg.getLayoutParams();
			 float leftMargin1 = MainTabActivity.this.getResources().getDimensionPixelSize(R.dimen.tab_container_bg_leftmargin);
			 TabIndicator tab = MainTabActivity.this.mPagerAdapter.getTab(position);
			 if(tab != null)
			 {
				 
				 float leftMargin2 = positionOffset * tab.getWidth();
				 float leftMargin3 = leftMargin1 + leftMargin2;
				 float rightMargin = 0.0F - leftMargin2;
				 for(int i =1; i <= position;i++)
				 {
					 leftMargin3 += tab.getWidth();
					 rightMargin -= tab.getWidth();
				 }
				 localLayoutParams.leftMargin = (int)leftMargin3;
				 localLayoutParams.rightMargin = (int)rightMargin;				  
				 MainTabActivity.this.mTabContainerBg.setLayoutParams(localLayoutParams);	    
			 }
			 else
				 MainTabActivity.this.mPager.setCurrentItem(position);
		}
	//public void onPageScrolled(int paramInt1, float paramFloat, int paramInt2)
		@Override
		public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {			 
			scrollTab(position,positionOffset);			 
		}

		@Override
		public void onPageSelected(int position) {
			// TODO Auto-generated method stub
			MainTabActivity.this.mPagerAdapter.selectTab(position);
			MainTabActivity.setCurrentTag(MainTabActivity.this, MainTabActivity.this.mPagerAdapter.getTagByPosition(position));
			setRequestedOrientation(2);
		}


		@Override
		public void onPageScrollStateChanged(int arg0) {
			// TODO Auto-generated method stub
			
		}
}
